package com.ulic.customerManApplication.commonmodule.action;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.base.BaseAction;
import com.ulic.customerManApplication.commonmodule.bo.Function;
import com.ulic.customerManApplication.commonmodule.bo.Menu;
import com.ulic.customerManApplication.commonmodule.bo.Organization;
import com.ulic.customerManApplication.commonmodule.service.OrganizationService;
import com.ulic.customerManApplication.tree.Tree;
import com.ulic.customerManApplication.tree.TreeBuilder;
import com.ulic.customerManApplication.tree.TreeNode;
import com.ulic.customerManApplication.usermodule.service.PermissionService;

@Component("organizationAction")
@Scope("prototype")
public class OrganizationAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static Tree reportTree;
	private Map<String, String> reportMap = new HashMap<String, String>();
	private static final String TRUE = "TRUE";
	private static final String FALSE = "FALSE";
	private static final String VLINE_IMAGE = "/html/image/treevertline.gif";
	private static final String BLANK_IMAGE = "/html/image/treeblank.gif";
	private static final String LAST_LEAF_IMAGE = "/html/image/treelastnode.gif";
	private static final String LEAF_IMAGE = "/html/image/treenode.gif";
	private static final String OPEN_BRANCH_IMGAGE = "/html/image/treemnode.gif";
	private static final String CLOSE_BRANCH_IMGAGE = "/html/image/treepnode.gif";
	private static final String LAST_OPEN_BRANCH_IMGAGE = "/html/image/treemlastnode.gif";
	private static final String LAST_CLOSE_BRANCH_IMGAGE = "/html/image/treeplastnode.gif";
	private static final String ROOT_IMAGE="/html/images/tree/base.gif";
	private static final String OPEN_IMAGE = "/html/images/open.gif";
	private static final String CLOSE_IMAGE = "/html/images/close.gif";
	private static final String PAGE_IMAGE = "/html/images/page.gif";
	
	private OrganizationService organizationService;
	private PermissionService permissionService;

	@Resource
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}
	@Resource
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public Tree getTree(String userOid) {
		if(reportTree == null) {
			rebuildReportTree(userOid);
		}
		return reportTree;
	}

	public String getNameLink(TreeNode tn) {
		return tn.getLink();
	}

	public String getNameLinkTarget() {
		return "info";
	}
	
	/**
	 * Description: 获得子机构
	 * @Version1.0 
	 * 2012-9-14 (liqz@huilan.com) created
	 * @param parentOid
	 * @return
	 * @throws Exception
	 */
	public Document findOrganizationByParentId(String parentOid) throws Exception{
		Document document = DocumentHelper.createDocument();
		Element objXmlElementRoot = document.addElement("root");
		Element objXmlElementList = objXmlElementRoot.addElement("list");
		List<Organization> organList = organizationService.findOrganizationByParentId(parentOid);
		if(organList!=null&&organList.size()>0){
			for(int i =0;i<organList.size();i++){
				Organization organ = organList.get(i);
				Element objXmlElementItem = objXmlElementList.addElement("item");
				String organname = organ.getAbbr_name();
				objXmlElementItem.addAttribute("name", organname);
				objXmlElementItem.addAttribute("oid", organ.getUm_organ_id());
			}
		}
		return document;
	}
	
	@SuppressWarnings("unchecked")
	private void rebuildReportTree(String userOid) {
		try {
			List<Menu> menuList = permissionService.getMenuPermissionList(Integer.parseInt(userOid));
			List<TreeNode> reportTreeNodeList = new ArrayList<TreeNode>();
			TreeNode rootNode = new TreeNode();
			String link = null;
			rootNode.setCode("-1");
			rootNode.setName("会员管理系统");
			rootNode.setParentCode("-2");
			rootNode.setSelected(true);
			rootNode.setOpen(false);
			rootNode.setHasLink(false);
			rootNode.setLink(link);
			reportMap.put(rootNode.getCode(), rootNode.getName());
			if(menuList!=null&&menuList.size()>0){
				for(int i=0;i<menuList.size();i++){
					Menu menu = menuList.get(i);
					if("管理员管理".equals(menu.getName())){
						TreeNode tn = new TreeNode();
						tn.setCode(menu.getCode());
						tn.setParentCode(rootNode.getCode());
						tn.setName(menu.getName());
						tn.setOpen(false);
						tn.setHasLink(false);
						tn.setLink(link);
						reportTreeNodeList.add(tn);
						reportMap.put(tn.getCode(), tn.getName());
						InputStream in = this.getClass().getResourceAsStream("/ReportTree.properties");
						BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8"));
						String line = null;
						while((line = br.readLine()) != null){
							line = line.trim();
							if(line!=null && line.length()!=0){
								String[] properties = line.split(",");
								String code = properties[0];
								String parentCode = properties[1].equals("-1")?tn.getCode():properties[1];
								String name = properties[2];
								String isOpen = properties[3];
								String hasLink = properties[4];
								if(properties.length > 5){
									link = properties[5];
								}
								reportMap.put(code, name);
								TreeNode tn1 = new TreeNode();
								tn1.setCode(code);
								tn1.setParentCode(parentCode);
								tn1.setName(name);
								tn1.setOpen("true".equalsIgnoreCase(isOpen));
								tn1.setHasLink("true".equalsIgnoreCase(hasLink));
								tn1.setLink(link);
								reportTreeNodeList.add(tn1);
							}
						}
					}else{
						TreeNode tn = new TreeNode();
						tn.setCode(menu.getCode());
						tn.setParentCode(rootNode.getCode());
						tn.setName(menu.getName());
						tn.setOpen(false);
						tn.setHasLink(false);
						tn.setLink(link);
						reportTreeNodeList.add(tn);
						reportMap.put(tn.getCode(), tn.getName());
						Set<Function> functions = menu.getFunctions();
						if(functions!=null&&functions.size()>0){
							Iterator iter = functions.iterator();
							while(iter.hasNext()){
								Function function = (Function)iter.next();
								TreeNode tn1 = new TreeNode();
								tn1.setCode(function.getCode());
								tn1.setParentCode(menu.getCode());
								tn1.setName(function.getName());
								tn1.setOpen(false);
								tn1.setHasLink(true);
								tn1.setLink(function.getUrl());
								reportTreeNodeList.add(tn1);
								reportMap.put(tn1.getCode(), tn1.getName());
							}
						}
					}
				}
			}
			reportTree = TreeBuilder.build(rootNode, reportTreeNodeList);
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public String getLink(TreeNode tn) {
		return "javascript:callTreeService('" + tn.getCode() + "')";
	}

	public String getTreeHTML(String code,String userOid,String contextPath) throws Exception {
		StringBuffer buffer = new StringBuffer();
		Tree tree = getTree(userOid);
		
		TreeNode tn = tree.getNode(code);
		tn.setOpen(!tn.isOpen());
		
		TreeNode rootNode = tree.getRootNode();
		assembleRoot(buffer, rootNode,contextPath);
        List<TreeNode> childNodes = rootNode.getChildNodes();
        
        for (int i = 0, size = childNodes.size(); i < size; i++) {
            render(tree, buffer, new ArrayList<String>(), childNodes.get(i), i == size - 1 ? true : false,contextPath);
        } 
		return buffer.toString();
	}
	
	public String clickNode(String code,String userOid,String contextPath) throws Exception {
		StringBuffer buffer = new StringBuffer();
		Tree tree = getTree(userOid);
		
		tree.clearSelectedState();
		TreeNode tn = tree.getNode(code);
		if(tn != null)
			tn.setSelected(true);
		
		TreeNode rootNode = tree.getRootNode();
		assembleRoot(buffer, rootNode,contextPath);
		
        List<TreeNode> childNodes = rootNode.getChildNodes();
        
        for (int i = 0, size = childNodes.size(); i < size; i++) {
            render(tree, buffer, new ArrayList<String>(), childNodes.get(i), i == size - 1 ? true : false,contextPath);
        }
		return buffer.toString();
	}

	protected void assembleRoot(StringBuffer sb, TreeNode treeNode,String contextPath) {
		sb.append("<table cellspacing=\"0\" cellpadding=\"4\" border=\"0\">");
		sb.append("<td><img src='"+contextPath+ROOT_IMAGE+"'/></td>");
		if(treeNode.isSelected()){
			sb.append("<td nowrap=\"nowrap\" id=\"1\" >");
		} else {
			sb.append("<td nowrap=\"nowrap\" id=\"1\">");
		}
		// name link
		String nameLink = getNameLink(treeNode);
		if(treeNode.isHasLink()) {
			sb.append("<a href=\"javascript:treeCurrentNode('" + nameLink + "');");
			sb.append("\" style=\"");
			sb.append("text-decoration:none;");
			sb.append(" >");
		}// has link

		sb.append("<font style='font-size:12px;'><b>"+treeNode.getName()+"</b></font>");
		
		if(treeNode.isHasLink()) {
			sb.append("</a>");
		}//has link
		
		sb.append("</td>");
		sb.append("</table>");
	}

	protected void render(Tree sourceTree, StringBuffer buffer, List<String> flags,
			TreeNode treeNode, boolean last,String contextPath) throws Exception {
		if (treeNode == null)
			return;
		buffer
				.append("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
		for (int i = 0, size = flags.size(); i < size; i++) {
			if (((String) flags.get(i)).equalsIgnoreCase(TRUE)) {
				buffer.append("<td nowrap=\"nowrap\"><img src=\"").append(
						contextPath).append(VLINE_IMAGE).append("\"/></td>");
			} else if (((String) flags.get(i)).equalsIgnoreCase(FALSE)) {
				buffer.append("<td nowrap=\"nowrap\"><img src=\"").append(
						contextPath).append(BLANK_IMAGE).append("\"/></td>");
			}
		}

		if (!treeNode.hasChildren()) {
			buffer.append("<td nowrap=\"nowrap\"><img src=\"").append(
					contextPath);
			if (last) {
				buffer.append(LAST_LEAF_IMAGE);
			} else {
				buffer.append(LEAF_IMAGE);
			}
			buffer.append("\" border=\"0\"/>");
			buffer.append("<img src='"+contextPath+PAGE_IMAGE+"' border=\"0\"/>");
			buffer.append("</td>");
		} else {
			buffer.append("<td nowrap=\"nowrap\">");
			buffer.append("<a href=\"");
			buffer.append(getLink(treeNode));
			buffer.append("\"");
			buffer.append(" >");
			// image
			buffer.append("<img src=\"").append(contextPath);
			if (last) {
				if (treeNode.isOpen()) {
					buffer.append(LAST_OPEN_BRANCH_IMGAGE);
				} else {
					buffer.append(LAST_CLOSE_BRANCH_IMGAGE);
				}
			} else {
				if (treeNode.isOpen()) {
					buffer.append(OPEN_BRANCH_IMGAGE);
				} else {
					buffer.append(CLOSE_BRANCH_IMGAGE);
				}
			}
			buffer.append("\" border=\"0\"/>");
			//文件夹 image
			buffer.append("<img src=\"").append(contextPath);
			if (treeNode.isOpen()) {
				buffer.append(OPEN_IMAGE);
			} else {
				buffer.append(CLOSE_IMAGE);
			}
			buffer.append("\" border=\"0\"/>");
			buffer.append("</a>");
			buffer.append("</td>");
		}
		if(treeNode.isSelected()){
			buffer.append("<td nowrap=\"nowrap\" style=\"padding:0 1px;\" id=\"" + treeNode.getCode() + "\">");
		} else {
			buffer.append("<td nowrap=\"nowrap\" style=\"padding:0 1px;\" id=\"" + treeNode.getCode() + "\">");
		}
		String nameLink = getNameLink(treeNode);
		if(treeNode.isHasLink()) {
			buffer.append("<a href=\"javascript:treeCurrentNode('" + nameLink + "');");
			buffer.append("\" style=\"text-decoration:none;");
			if(treeNode.isSelected()){
				buffer.append("color:#fff;font-weight:bold;");
			}
			buffer.append("\"");
			buffer.append(" >");
		}// has link

		buffer.append("<font style='font-size:12px;'>"+treeNode.getName()+"</font>");
		if(treeNode.isHasLink()) {
			buffer.append("</a>");
		}// has link
		buffer.append("</td>");
		// current node end
		buffer.append("</table>");
		List<TreeNode> childNodes = treeNode.getChildNodes();
		if (treeNode.isOpen()
				&& childNodes != null && childNodes.size() > 0) {
			if (last) {
				flags.add(FALSE);
			} else {
				flags.add(TRUE);
			}
			for (int i = 0, size = childNodes.size(); i < size; i++) {
				render(sourceTree, buffer, flags, (TreeNode) childNodes.get(i),
						i == size - 1 ? true : false,contextPath);
			}
		}
		if (last) {
			if (flags.size() > 0) {
				flags.remove(flags.size() - 1);
			}
		}
	}

}
